extends Window
class_name InventoryWindow

## 背包装备窗口
## 包含装备栏和背包界面，支持拖拽操作

# PlayerHUD引用，用于获取正确的界面尺寸
var player_hud: Control = null

@onready var equipment_panel: Control = $HBoxContainer/EquipmentPanel
@onready var inventory_panel: Control = $HBoxContainer/InventoryPanel
@onready var tab_container: TabContainer = $HBoxContainer/InventoryPanel/VBoxContainer/TabContainer
@onready var gold_label: Label = $HBoxContainer/InventoryPanel/VBoxContainer/BottomPanel/HBoxContainer/GoldLabel
@onready var sell_button: Button = $HBoxContainer/InventoryPanel/VBoxContainer/BottomPanel/HBoxContainer/SellButton
@onready var select_all_button: Button = $HBoxContainer/InventoryPanel/VBoxContainer/BottomPanel/HBoxContainer/SelectAllButton
@onready var sort_button: Button = $HBoxContainer/InventoryPanel/VBoxContainer/BottomPanel/HBoxContainer/SortButton

# 确认面板相关节点（现在是悬浮在背包中央）
@onready var confirm_panel: Panel = $HBoxContainer/InventoryPanel/ConfirmPanel
@onready var confirm_label: Label = $HBoxContainer/InventoryPanel/ConfirmPanel/VBoxContainer/ConfirmLabel
@onready var confirm_sell_button: Button = $HBoxContainer/InventoryPanel/ConfirmPanel/VBoxContainer/HBoxContainer/ConfirmSellButton
@onready var cancel_sell_button: Button = $HBoxContainer/InventoryPanel/ConfirmPanel/VBoxContainer/HBoxContainer/CancelSellButton

# 物品信息面板
@onready var item_info_panel: Panel = $HBoxContainer/ItemInfoPanel
@onready var item_info_label: RichTextLabel = $HBoxContainer/ItemInfoPanel/VBoxContainer/ScrollContainer/InfoLabel
@onready var enhance_button: Button = $HBoxContainer/ItemInfoPanel/VBoxContainer/EnhanceButton

# 装备栏槽位
@onready var weapon_slot: Control = $HBoxContainer/EquipmentPanel/EquipmentContainer/WeaponSlot
@onready var shield_slot: Control = $HBoxContainer/EquipmentPanel/EquipmentContainer/ShieldSlot
@onready var helmet_slot: Control = $HBoxContainer/EquipmentPanel/EquipmentContainer/HelmetSlot
@onready var legs_slot: Control = $HBoxContainer/EquipmentPanel/EquipmentContainer/LegsSlot
@onready var chest_slot: Control = $HBoxContainer/EquipmentPanel/EquipmentContainer/ChestSlot
@onready var gloves_slot: Control = $HBoxContainer/EquipmentPanel/EquipmentContainer/GlovesSlot
@onready var boots_slot: Control = $HBoxContainer/EquipmentPanel/EquipmentContainer/BootsSlot
@onready var ring1_slot: Control = $HBoxContainer/EquipmentPanel/EquipmentContainer/Ring1Slot
@onready var ring2_slot: Control = $HBoxContainer/EquipmentPanel/EquipmentContainer/Ring2Slot
@onready var necklace_slot: Control = $HBoxContainer/EquipmentPanel/EquipmentContainer/NecklaceSlot
@onready var earring_slot: Control = $HBoxContainer/EquipmentPanel/EquipmentContainer/EarringSlot

# 背包网格
@onready var equipment_grid: GridContainer = $HBoxContainer/InventoryPanel/VBoxContainer/TabContainer/装备/ScrollContainer/EquipmentGrid
@onready var consumable_grid: GridContainer = $HBoxContainer/InventoryPanel/VBoxContainer/TabContainer/消耗品/ScrollContainer/ConsumableGrid
@onready var material_grid: GridContainer = $HBoxContainer/InventoryPanel/VBoxContainer/TabContainer/材料/ScrollContainer/MaterialGrid

# 属性显示面板已移除，现在使用独立的角色属性窗口

var equipment_slots: Dictionary = {}
var inventory_slots: Dictionary = {}

# 拖拽系统变量
var dragging_item: Control = null
var drag_preview: Control = null
var drag_source_slot: Control = null
var drag_source_type: String = ""  # "equipment" 或 "inventory"
var drag_source_index: int = -1
var drag_source_item_type = null
var drag_item_data = null
var is_dragging: bool = false

# 双击检测变量
var last_click_time: float = 0.0
var last_clicked_slot: Control = null
const DOUBLE_CLICK_TIME: float = 0.5  # 双击时间间隔（秒）

# 单击拖拽区分变量
var mouse_press_time: float = 0.0
var mouse_press_slot: Control = null
var is_mouse_pressed: bool = false
const DRAG_THRESHOLD_TIME: float = 0.2  # 拖拽阈值时间（秒）

# 当前选中的槽位
var selected_slot = null
var selected_slot_type = ""
var selected_slot_index = -1

# 当前选中的背包物品
var selected_inventory_slot = null
var selected_inventory_type = null
var selected_inventory_index = -1

# 当前选中的装备槽
var selected_equipment_slot = null
var selected_equipment_type = null

# 卖出相关 - 移除独立卖出模式，集成到基础功能中
var selected_items_for_sale = []  # 存储选中要卖出的物品信息

# 强化相关变量
var current_enhance_item: ItemManager.EquipmentData = null
var current_enhance_slot_type = null
var current_enhance_inventory_type = null
var current_enhance_inventory_index: int = -1
var current_enhancement_result_panel: Panel = null
# UI锁定状态，用于强化期间禁用所有交互
var is_ui_locked: bool = false

const SLOT_SIZE = Vector2(64, 64)
const INVENTORY_COLS = 5
const INVENTORY_ROWS = 40

signal item_equipped(slot, item)
signal item_unequipped(slot)
signal item_used(item)

func _ready():
	_setup_window()
	_create_equipment_slots()
	_create_inventory_grids()
	_connect_signals()
	_update_display()
	_clear_inventory_selection()  # 初始化时清除背包物品选中状态
	_clear_equipment_selection()  # 初始化时清除装备选中状态
	
	# 连接按钮信号
	sell_button.pressed.connect(_on_sell_button_pressed)
	select_all_button.pressed.connect(_on_select_all_button_pressed)
	sort_button.pressed.connect(_on_sort_button_pressed)
	confirm_sell_button.pressed.connect(_on_confirm_sell_pressed)
	cancel_sell_button.pressed.connect(_on_cancel_sell_pressed)
	enhance_button.pressed.connect(_on_enhance_button_pressed)
	
	# 连接标签页切换信号
	tab_container.tab_changed.connect(_on_tab_changed)
	
	# 显示全选按钮，作为基础功能
	select_all_button.visible = true
	select_all_button.text = "全选"
	
	# 初始化金币显示
	_update_gold_display(PlayerStatsManager.get_gold())
	
	# 初始化物品信息面板为常驻显示
	item_info_label.text = "点击物品查看详细信息"
	item_info_panel.visible = true

func _input(event: InputEvent):
	# 检查UI是否被锁定
	if is_ui_locked:
		return
	
	# 处理拖拽过程中的鼠标移动和释放
	if is_dragging:
		if event is InputEventMouseMotion:
			_update_drag_preview(event.global_position)
		elif event is InputEventMouseButton and event.button_index == MOUSE_BUTTON_LEFT and not event.pressed:
			_end_drag(event.global_position)
	
	# 检查长按是否应该开始拖拽
	if is_mouse_pressed and not is_dragging:
		var current_time = Time.get_ticks_msec() / 1000.0
		var press_duration = current_time - mouse_press_time
		if press_duration >= DRAG_THRESHOLD_TIME:
			_check_start_drag_from_long_press()

func _check_start_drag_from_long_press():
	## 检查长按是否应该开始拖拽
	if not mouse_press_slot:
		return
	
	# 检查是否是装备槽
	for slot_type in equipment_slots:
		if equipment_slots[slot_type] == mouse_press_slot:
			var equipment = ItemManager.get_equipped_item(slot_type)
			if equipment != null:
				_start_drag(mouse_press_slot, equipment, "equipment", slot_type)
				is_mouse_pressed = false
				mouse_press_slot = null
			return
	
	# 检查是否是背包槽
	for item_type in inventory_slots:
		for i in range(inventory_slots[item_type].size()):
			if inventory_slots[item_type][i] == mouse_press_slot:
				var inventory = ItemManager.get_inventory_by_type(item_type)
				if i < inventory.size():
					var inventory_slot = inventory[i]
					if not inventory_slot.is_empty():
						_start_drag(mouse_press_slot, inventory_slot.item_data, "inventory", i, item_type)
						is_mouse_pressed = false
						mouse_press_slot = null
				return

func _is_double_click(slot_ui: Control) -> bool:
	## 检测是否为双击
	# 使用Time.get_ticks_msec()获取毫秒级时间戳，更准确且避免字典访问错误
	var current_timestamp = Time.get_ticks_msec() / 1000.0
	
	if last_clicked_slot == slot_ui and (current_timestamp - last_click_time) <= DOUBLE_CLICK_TIME:
		last_clicked_slot = null
		last_click_time = 0.0
		return true
	else:
		last_clicked_slot = slot_ui
		last_click_time = current_timestamp
		return false

func _setup_window():
	title = "背包装备"
	
	# 设置最小尺寸限制
	var min_width = 600
	var min_height = 400
	min_size = Vector2(min_width, min_height)
	
	unresizable = false
	always_on_top = true
	close_requested.connect(_on_close_requested)

func _setup_window_size():
	"""动态设置窗口大小"""
	# 获取PlayerHUD大小
	var player_hud_size = player_hud.size if player_hud else get_viewport().get_visible_rect().size
	
	# 设置窗口大小为PlayerHUD大小减去像素
	size = Vector2i(int(player_hud_size.x), int(player_hud_size.y - 40))
	position = Vector2i(0, 35)

func _create_equipment_slots():
	var slot_configs = {
		ItemManager.EquipmentSlot.WEAPON: {"node": weapon_slot, "name": "武器"},
		ItemManager.EquipmentSlot.SHIELD: {"node": shield_slot, "name": "盾牌"},
		ItemManager.EquipmentSlot.HELMET: {"node": helmet_slot, "name": "头盔"},
		ItemManager.EquipmentSlot.CHEST: {"node": chest_slot, "name": "胸甲"},
		ItemManager.EquipmentSlot.LEGS: {"node": legs_slot, "name": "护腿"},
		ItemManager.EquipmentSlot.GLOVES: {"node": gloves_slot, "name": "手套"},
		ItemManager.EquipmentSlot.BOOTS: {"node": boots_slot, "name": "鞋子"},
		ItemManager.EquipmentSlot.RING1: {"node": ring1_slot, "name": "戒指1"},
		ItemManager.EquipmentSlot.RING2: {"node": ring2_slot, "name": "戒指2"},
		ItemManager.EquipmentSlot.NECKLACE: {"node": necklace_slot, "name": "项链"},
		ItemManager.EquipmentSlot.EARRING: {"node": earring_slot, "name": "耳环"}
	}
	
	for slot_type in slot_configs:
		var config = slot_configs[slot_type]
		var slot_ui = _create_equipment_slot_ui(slot_type, config.name)
		if config.node:
			config.node.add_child(slot_ui)
			equipment_slots[slot_type] = slot_ui

func _create_equipment_slot_ui(slot_type, slot_name: String) -> Control:
	var slot_container = Control.new()
	slot_container.custom_minimum_size = SLOT_SIZE
	slot_container.size = SLOT_SIZE
	
	# 创建带边框的背景面板
	var background = Panel.new()
	background.size = SLOT_SIZE
	background.anchors_preset = Control.PRESET_FULL_RECT
	
	# 创建样式资源并设置边框
	var style_box = StyleBoxFlat.new()
	style_box.bg_color = Color(0.2, 0.2, 0.3, 0.9)  # 深蓝灰色背景
	style_box.border_width_left = 2
	style_box.border_width_right = 2
	style_box.border_width_top = 2
	style_box.border_width_bottom = 2
	style_box.border_color = Color(0.6, 0.6, 0.8, 1.0)  # 浅蓝色边框
	style_box.corner_radius_top_left = 4
	style_box.corner_radius_top_right = 4
	style_box.corner_radius_bottom_left = 4
	style_box.corner_radius_bottom_right = 4
	background.add_theme_stylebox_override("panel", style_box)
	slot_container.add_child(background)
	
	var label = Label.new()
	label.text = slot_name
	label.size = SLOT_SIZE
	label.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTER
	label.vertical_alignment = VERTICAL_ALIGNMENT_CENTER
	label.add_theme_font_size_override("font_size", 10)
	slot_container.add_child(label)
	
	var item_icon = TextureRect.new()
	item_icon.name = "ItemIcon"
	item_icon.size = SLOT_SIZE
	item_icon.expand_mode = TextureRect.EXPAND_FIT_WIDTH_PROPORTIONAL
	item_icon.stretch_mode = TextureRect.STRETCH_KEEP_ASPECT_CENTERED
	item_icon.visible = false
	slot_container.add_child(item_icon)
	
	var enhancement_label = Label.new()
	enhancement_label.name = "EnhancementLabel"
	enhancement_label.size = Vector2(20, 20)
	enhancement_label.position = Vector2(SLOT_SIZE.x - 20, 0)
	enhancement_label.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTER
	enhancement_label.vertical_alignment = VERTICAL_ALIGNMENT_CENTER
	enhancement_label.add_theme_font_size_override("font_size", 8)
	enhancement_label.add_theme_color_override("font_color", Color.YELLOW)
	enhancement_label.visible = false
	slot_container.add_child(enhancement_label)
	
	slot_container.gui_input.connect(_on_equipment_slot_input.bind(slot_type))
	slot_container.mouse_entered.connect(_on_slot_mouse_entered.bind(slot_container, slot_type))
	slot_container.mouse_exited.connect(_on_slot_mouse_exited)
	
	return slot_container

func _create_inventory_grids():
	_setup_inventory_grid(equipment_grid, ItemManager.ItemType.EQUIPMENT)
	_setup_inventory_grid(consumable_grid, ItemManager.ItemType.CONSUMABLE)
	_setup_inventory_grid(material_grid, ItemManager.ItemType.MATERIAL)

func _setup_inventory_grid(grid: GridContainer, item_type):
	grid.columns = INVENTORY_COLS
	
	for i in range(ItemManager.INVENTORY_SIZE):
		var slot_ui = _create_inventory_slot_ui(item_type, i)
		grid.add_child(slot_ui)
		if not inventory_slots.has(item_type):
			inventory_slots[item_type] = []
		inventory_slots[item_type].append(slot_ui)

func _create_inventory_slot_ui(item_type, index: int) -> Control:
	var slot_container = Control.new()
	slot_container.custom_minimum_size = SLOT_SIZE
	slot_container.size = SLOT_SIZE
	
	# 创建带边框的背景面板
	var background = Panel.new()
	background.size = SLOT_SIZE
	background.anchors_preset = Control.PRESET_FULL_RECT
	
	# 创建样式资源并设置边框
	var style_box = StyleBoxFlat.new()
	style_box.bg_color = Color(0.15, 0.15, 0.15, 0.9)  # 深灰色背景
	style_box.border_width_left = 1
	style_box.border_width_right = 1
	style_box.border_width_top = 1
	style_box.border_width_bottom = 1
	style_box.border_color = Color(0.5, 0.5, 0.5, 1.0)  # 灰色边框
	style_box.corner_radius_top_left = 3
	style_box.corner_radius_top_right = 3
	style_box.corner_radius_bottom_left = 3
	style_box.corner_radius_bottom_right = 3
	background.add_theme_stylebox_override("panel", style_box)
	slot_container.add_child(background)
	
	var item_icon = TextureRect.new()
	item_icon.name = "ItemIcon"
	item_icon.size = SLOT_SIZE
	item_icon.expand_mode = TextureRect.EXPAND_FIT_WIDTH_PROPORTIONAL
	item_icon.stretch_mode = TextureRect.STRETCH_KEEP_ASPECT_CENTERED
	item_icon.visible = false
	slot_container.add_child(item_icon)
	
	var quantity_label = Label.new()
	quantity_label.name = "QuantityLabel"
	quantity_label.size = Vector2(20, 20)
	quantity_label.position = Vector2(SLOT_SIZE.x - 20, SLOT_SIZE.y - 20)
	quantity_label.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTER
	quantity_label.vertical_alignment = VERTICAL_ALIGNMENT_CENTER
	quantity_label.add_theme_font_size_override("font_size", 10)
	quantity_label.add_theme_color_override("font_color", Color.WHITE)
	quantity_label.visible = false
	slot_container.add_child(quantity_label)
	
	var enhancement_label = Label.new()
	enhancement_label.name = "EnhancementLabel"
	enhancement_label.size = Vector2(20, 20)
	enhancement_label.position = Vector2(SLOT_SIZE.x - 20, 0)
	enhancement_label.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTER
	enhancement_label.vertical_alignment = VERTICAL_ALIGNMENT_CENTER
	enhancement_label.add_theme_font_size_override("font_size", 8)
	enhancement_label.add_theme_color_override("font_color", Color.YELLOW)
	enhancement_label.visible = false
	slot_container.add_child(enhancement_label)
	
	slot_container.gui_input.connect(_on_inventory_slot_input.bind(item_type, index))
	slot_container.mouse_entered.connect(_on_inventory_slot_mouse_entered.bind(slot_container, item_type, index))
	slot_container.mouse_exited.connect(_on_slot_mouse_exited)
	
	return slot_container

func _connect_signals():
	# 延迟连接信号，确保ItemManager完全初始化
	await get_tree().process_frame
	if ItemManager != null:
		ItemManager.connect("equipment_changed", _on_equipment_changed)
		ItemManager.connect("inventory_changed", _on_inventory_changed)
		PlayerStatsManager.gold_changed.connect(_update_gold_display)
		print("信号连接成功")
	else:
		print("ItemManager不可用")

func _start_drag(slot_ui: Control, item_data, source_type: String, source_index: int = -1, item_type = null):
	## 开始拖拽操作
	if is_dragging or item_data == null:
		return
	
	is_dragging = true
	drag_source_slot = slot_ui
	drag_source_type = source_type
	drag_source_index = source_index
	drag_item_data = item_data
	
	# 存储物品类型信息（用于inventory类型的拖拽）
	if source_type == "inventory" and item_type != null:
		drag_source_item_type = item_type
	elif source_type == "equipment":
		# 对于装备槽，source_index实际上是slot_type
		drag_source_index = source_index
	
	# 创建拖拽预览
	_create_drag_preview()
	
	# 设置源槽位的视觉反馈
	var background = slot_ui.get_child(0) as Panel
	if background:
		var style_box = background.get_theme_stylebox("panel").duplicate() as StyleBoxFlat
		style_box.bg_color = Color(0.5, 0.5, 0.5, 0.5)  # 半透明表示正在拖拽
		background.add_theme_stylebox_override("panel", style_box)

func _create_drag_preview():
	## 创建拖拽预览控件
	if drag_preview:
		drag_preview.queue_free()
	
	drag_preview = Control.new()
	drag_preview.size = SLOT_SIZE
	drag_preview.z_index = 1000  # 确保在最上层
	drag_preview.mouse_filter = Control.MOUSE_FILTER_IGNORE  # 忽略鼠标事件，避免干扰拖拽
	drag_preview.top_level = true  # 确保不受父节点变换影响
	
	# 添加背景
	var background = Panel.new()
	background.size = SLOT_SIZE
	background.anchors_preset = Control.PRESET_FULL_RECT
	var style_box = StyleBoxFlat.new()
	style_box.bg_color = Color(0.2, 0.2, 0.2, 0.9)  # 半透明深色背景
	style_box.border_width_left = 3
	style_box.border_width_right = 3
	style_box.border_width_top = 3
	style_box.border_width_bottom = 3
	style_box.border_color = Color(1.0, 0.8, 0.0, 1.0)  # 金色边框表示拖拽中
	style_box.corner_radius_top_left = 4
	style_box.corner_radius_top_right = 4
	style_box.corner_radius_bottom_left = 4
	style_box.corner_radius_bottom_right = 4
	background.add_theme_stylebox_override("panel", style_box)
	background.mouse_filter = Control.MOUSE_FILTER_IGNORE
	drag_preview.add_child(background)
	
	# 添加物品图标
	var icon = TextureRect.new()
	icon.size = SLOT_SIZE - Vector2(6, 6)  # 稍微小一点，留出边框空间
	icon.position = Vector2(3, 3)  # 居中显示
	icon.expand_mode = TextureRect.EXPAND_FIT_WIDTH_PROPORTIONAL
	icon.stretch_mode = TextureRect.STRETCH_KEEP_ASPECT_CENTERED
	icon.mouse_filter = Control.MOUSE_FILTER_IGNORE
	
	# 加载物品图标
	if drag_item_data and drag_item_data.icon_path != "":
		if ResourceLoader.exists(drag_item_data.icon_path):
			icon.texture = load(drag_item_data.icon_path)
			print("拖拽预览加载图标：", drag_item_data.icon_path)
		else:
			print("拖拽预览图标文件不存在：", drag_item_data.icon_path)
	else:
		print("拖拽预览无图标路径")
	
	drag_preview.add_child(icon)
	
	# 如果是装备，添加强化等级标签
	if drag_item_data and drag_item_data.type == ItemManager.ItemType.EQUIPMENT:
		var equipment = drag_item_data as ItemManager.EquipmentData
		if equipment.enhancement_level > 0:
			var enhancement_label = Label.new()
			enhancement_label.text = "+" + str(equipment.enhancement_level)
			enhancement_label.size = Vector2(20, 20)
			enhancement_label.position = Vector2(SLOT_SIZE.x - 23, 3)
			enhancement_label.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTER
			enhancement_label.vertical_alignment = VERTICAL_ALIGNMENT_CENTER
			enhancement_label.add_theme_font_size_override("font_size", 8)
			enhancement_label.add_theme_color_override("font_color", Color.YELLOW)
			enhancement_label.mouse_filter = Control.MOUSE_FILTER_IGNORE
			drag_preview.add_child(enhancement_label)
	
	# 如果是消耗品且数量大于1，添加数量标签
	if drag_source_type == "inventory" and drag_source_item_type == ItemManager.ItemType.CONSUMABLE:
		var inventory = ItemManager.get_inventory_by_type(drag_source_item_type)
		if drag_source_index < inventory.size():
			var inventory_slot = inventory[drag_source_index]
			if inventory_slot.quantity > 1:
				var quantity_label = Label.new()
				quantity_label.text = str(inventory_slot.quantity)
				quantity_label.size = Vector2(20, 20)
				quantity_label.position = Vector2(SLOT_SIZE.x - 23, SLOT_SIZE.y - 23)
				quantity_label.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTER
				quantity_label.vertical_alignment = VERTICAL_ALIGNMENT_CENTER
				quantity_label.add_theme_font_size_override("font_size", 10)
				quantity_label.add_theme_color_override("font_color", Color.WHITE)
				quantity_label.mouse_filter = Control.MOUSE_FILTER_IGNORE
				drag_preview.add_child(quantity_label)
	
	# 添加到当前窗口，确保在最上层
	get_viewport().add_child(drag_preview)
	# 初始化位置
	_update_drag_preview(get_viewport().get_mouse_position())
	print("拖拽预览已创建：", drag_item_data.name if drag_item_data else "未知物品")

func _update_drag_preview(global_position: Vector2):
	## 更新拖拽预览位置
	if drag_preview:
		drag_preview.global_position = global_position - SLOT_SIZE / 2

func _end_drag(global_position: Vector2):
	## 结束拖拽操作
	if not is_dragging:
		return
	
	# 查找目标槽位
	var target_slot = _find_slot_at_position(global_position)
	if target_slot:
		_handle_drop(target_slot)
	else:
		print("拖拽到无效位置")
	
	# 清理拖拽状态
	_cleanup_drag()

func _find_slot_at_position(global_position: Vector2) -> Control:
	## 查找指定位置的槽位
	# 优先检查当前可见的背包标签页
	var current_tab = tab_container.current_tab
	var tab_names = [ItemManager.ItemType.EQUIPMENT, ItemManager.ItemType.CONSUMABLE, ItemManager.ItemType.MATERIAL]
	
	if current_tab < tab_names.size():
		var current_item_type = tab_names[current_tab]
		if current_item_type in inventory_slots:
			for slot_ui in inventory_slots[current_item_type]:
				if slot_ui.get_global_rect().has_point(global_position):
					return slot_ui
	
	# 检查装备槽
	for slot_ui in equipment_slots.values():
		if slot_ui.get_global_rect().has_point(global_position):
			return slot_ui
	
	# 检查其他背包槽（如果当前标签页没有匹配）
	for item_type in inventory_slots:
		for slot_ui in inventory_slots[item_type]:
			if slot_ui.get_global_rect().has_point(global_position):
				return slot_ui
	
	return null

func _handle_drop(target_slot: Control):
	## 处理拖拽放置逻辑
	var target_type = ""
	var target_index = -1
	var target_slot_type = null
	var target_item_type = null
	
	# 确定目标槽位类型
	for slot_type in equipment_slots:
		if equipment_slots[slot_type] == target_slot:
			target_type = "equipment"
			target_slot_type = slot_type
			break
	
	if target_type == "":
		for item_type in inventory_slots:
			for i in range(inventory_slots[item_type].size()):
				if inventory_slots[item_type][i] == target_slot:
					target_type = "inventory"
					target_index = i
					target_item_type = item_type
					break
			if target_type != "":
				break
	
	# 执行拖拽逻辑
	if drag_source_type == "equipment" and target_type == "inventory":
		_move_equipment_to_inventory(target_index, target_item_type)
	elif drag_source_type == "inventory" and target_type == "equipment":
		_move_inventory_to_equipment(target_slot_type)
	elif drag_source_type == "inventory" and target_type == "inventory":
		_swap_inventory_items(target_index, target_item_type)
	elif drag_source_type == "equipment" and target_type == "equipment":
		_swap_equipment_items(target_slot_type)
	else:
		print("无效的拖拽操作")

func _cleanup_drag():
	## 清理拖拽状态
	is_dragging = false
	
	# 移除拖拽预览
	if drag_preview:
		drag_preview.queue_free()
		drag_preview = null
	
	# 恢复源槽位样式
	if drag_source_slot:
		_restore_slot_style(drag_source_slot)
	
	# 重置拖拽变量
	drag_source_slot = null
	drag_source_type = ""
	drag_source_index = -1
	drag_source_item_type = null
	drag_item_data = null

func _restore_slot_style(slot_ui: Control):
	## 恢复槽位原始样式
	var background = slot_ui.get_child(0) as Panel
	if background:
		var style_box = background.get_theme_stylebox("panel").duplicate() as StyleBoxFlat
		if drag_source_type == "equipment":
			style_box.bg_color = Color(0.2, 0.2, 0.3, 0.9)
		else:
			style_box.bg_color = Color(0.15, 0.15, 0.15, 0.9)
		background.add_theme_stylebox_override("panel", style_box)

func _move_equipment_to_inventory(target_index: int, target_item_type):
	## 将装备移动到背包
	# drag_source_index现在存储的是slot_type
	var source_slot_type = drag_source_index
	
	if source_slot_type != null:
		# 检查目标背包类型，装备只能移动到装备背包
		if target_item_type == ItemManager.ItemType.EQUIPMENT:
			# 检查目标位置是否为空
			var target_inventory = ItemManager.get_inventory_by_type(target_item_type)
			if target_index < target_inventory.size() and target_inventory[target_index].is_empty():
				# 目标位置为空，直接卸载到该位置
				if ItemManager.unequip_item(source_slot_type):
					print("装备已卸下到指定位置：", drag_item_data.name)
					item_unequipped.emit(source_slot_type)
			else:
				# 目标位置有物品，检查是否可以交换
				var target_item = target_inventory[target_index].item_data
				if target_item != null and target_item.type == ItemManager.ItemType.EQUIPMENT:
					var target_equipment = target_item as ItemManager.EquipmentData
					if ItemManager._can_equip_to_slot(target_equipment, source_slot_type):
						# 可以交换兼容的装备
						if ItemManager.swap_equipment_with_inventory(source_slot_type, target_index):
							print("装备已交换：", drag_item_data.name, " <-> ", target_equipment.name)
							item_unequipped.emit(source_slot_type)
							item_equipped.emit(source_slot_type, target_equipment)
					else:
						print("目标位置的装备类型不匹配")
				else:
					print("目标位置已被占用")
		else:
			print("装备只能移动到装备背包中")

func _move_inventory_to_equipment(target_slot_type):
	## 将背包物品装备到装备槽
	if drag_item_data.type == ItemManager.ItemType.EQUIPMENT and ItemManager._can_equip_to_slot(drag_item_data, target_slot_type):
		# 只有从装备背包拖拽的装备才能装备
		if drag_source_item_type == ItemManager.ItemType.EQUIPMENT:
			ItemManager.equip_item(drag_source_index)
			print("装备已装备：", drag_item_data.name)
		else:
			print("只能从装备背包装备物品")
	else:
		print("物品类型不匹配，无法装备")

func _swap_inventory_items(target_index: int, target_type):
	## 交换背包中的物品
	if drag_source_index != target_index or drag_source_item_type != target_type:
		# 确定源物品类型
		var source_type = drag_source_item_type
		
		if source_type != null and target_type != null:
			# 只允许同类型背包内的物品交换
			if source_type == target_type:
				ItemManager.swap_inventory_items(source_type, drag_source_index, target_type, target_index)
				print("物品位置已交换")
			else:
				print("不能在不同类型的背包间移动物品")
		else:
			print("无法确定物品类型，交换失败")

func _swap_equipment_items(target_slot_type):
	## 交换装备槽中的装备
	# drag_source_index现在存储的是slot_type
	var source_slot_type = drag_source_index
	
	if source_slot_type != null and source_slot_type != target_slot_type:
		# 获取源装备和目标装备
		var source_equipment = ItemManager.get_equipped_item(source_slot_type)
		var target_equipment = ItemManager.get_equipped_item(target_slot_type)
		
		# 验证装备类型匹配
		var can_swap = true
		
		# 检查源装备是否适合目标槽位
		if source_equipment != null and not ItemManager._can_equip_to_slot(source_equipment, target_slot_type):
			print("源装备 '%s' 不适合目标槽位 '%s'" % [source_equipment.name, _get_slot_display_name(target_slot_type)])
			can_swap = false
		
		# 检查目标装备是否适合源槽位
		if target_equipment != null and not ItemManager._can_equip_to_slot(target_equipment, source_slot_type):
			print("目标装备 '%s' 不适合源槽位 '%s'" % [target_equipment.name, _get_slot_display_name(source_slot_type)])
			can_swap = false
		
		if can_swap:
			ItemManager.swap_equipment_items(source_slot_type, target_slot_type)
			print("装备位置已交换")
		else:
			print("装备类型不匹配，无法交换")

func _update_display():
	_update_equipment_display()
	_update_inventory_display()

func _update_equipment_display():
	for slot_type in equipment_slots:
		var slot_ui = equipment_slots[slot_type]
		var equipment = ItemManager.get_equipped_item(slot_type)
		_update_equipment_slot_display(slot_ui, equipment)

func _update_equipment_slot_display(slot_ui: Control, equipment):
	var icon = slot_ui.get_node("ItemIcon")
	var enhancement_label = slot_ui.get_node("EnhancementLabel")
	
	if equipment != null:
		icon.visible = true
		if equipment.icon_path != "" and ResourceLoader.exists(equipment.icon_path):
			icon.texture = load(equipment.icon_path)
		
		if equipment.enhancement_level > 0:
			enhancement_label.visible = true
			enhancement_label.text = "+" + str(equipment.enhancement_level)
		else:
			enhancement_label.visible = false
	else:
		icon.visible = false
		enhancement_label.visible = false

func _update_inventory_display():
	for item_type in inventory_slots:
		var slots_ui = inventory_slots[item_type]
		var inventory = ItemManager.get_inventory_by_type(item_type)
		
		for i in range(min(slots_ui.size(), inventory.size())):
			var slot_ui = slots_ui[i]
			var inventory_slot = inventory[i]
			_update_inventory_slot_display(slot_ui, inventory_slot)

func _update_inventory_slot_display(slot_ui: Control, inventory_slot: ItemManager.InventorySlot):
	var icon = slot_ui.get_node("ItemIcon")
	var quantity_label = slot_ui.get_node("QuantityLabel")
	var enhancement_label = slot_ui.get_node("EnhancementLabel")
	var background = slot_ui.get_child(0) as Panel
	
	if not inventory_slot.is_empty():
		icon.visible = true
		var item_data = inventory_slot.item_data
		if item_data.icon_path != "" and ResourceLoader.exists(item_data.icon_path):
			icon.texture = load(item_data.icon_path)
		
		if inventory_slot.quantity > 1:
			quantity_label.visible = true
			quantity_label.text = str(inventory_slot.quantity)
		else:
			quantity_label.visible = false
		
		if item_data.type == ItemManager.ItemType.EQUIPMENT:
			var equipment = item_data as ItemManager.EquipmentData
			if equipment.enhancement_level > 0:
				enhancement_label.visible = true
				enhancement_label.text = "+" + str(equipment.enhancement_level)
			else:
				enhancement_label.visible = false
		else:
			enhancement_label.visible = false
		
		# 设置物品槽位样式
		if background:
			# 查找当前槽位的item_type和index
			var item_type = null
			var index = -1
			for type in inventory_slots:
				for i in range(inventory_slots[type].size()):
					if inventory_slots[type][i] == slot_ui:
						item_type = type
						index = i
						break
				if item_type != null:
					break
			
			if item_type != null and _is_item_selected_for_sale(item_type, index):
				# 选中状态 - 金色背景（表示已选中用于卖出）
				var style_box = StyleBoxFlat.new()
				style_box.bg_color = Color(0.8, 0.6, 0.2, 0.8)  # 金色背景
				style_box.border_width_left = 2
				style_box.border_width_right = 2
				style_box.border_width_top = 2
				style_box.border_width_bottom = 2
				style_box.border_color = Color(1.0, 0.8, 0.0, 1.0)  # 金色边框
				style_box.corner_radius_top_left = 3
				style_box.corner_radius_top_right = 3
				style_box.corner_radius_bottom_left = 3
				style_box.corner_radius_bottom_right = 3
				background.add_theme_stylebox_override("panel", style_box)
			else:
				# 未选中状态 - 根据稀有度设置边框颜色和背景颜色
				var style_box = StyleBoxFlat.new()
				# 根据物品稀有度设置边框颜色和背景颜色
				var rarity_color = ItemManager.get_rarity_color(item_data.rarity)
				# 设置半透明的稀有度背景颜色
				var bg_color = rarity_color
				bg_color.a = 0.15  # 设置为半透明
				style_box.bg_color = bg_color
				style_box.border_width_left = 2
				style_box.border_width_right = 2
				style_box.border_width_top = 2
				style_box.border_width_bottom = 2
				style_box.border_color = rarity_color
				style_box.corner_radius_top_left = 3
				style_box.corner_radius_top_right = 3
				style_box.corner_radius_bottom_left = 3
				style_box.corner_radius_bottom_right = 3
				background.add_theme_stylebox_override("panel", style_box)
	else:
		icon.visible = false
		quantity_label.visible = false
		enhancement_label.visible = false
		
		# 空槽位恢复原始样式
		if background:
			var style_box = StyleBoxFlat.new()
			style_box.bg_color = Color(0.15, 0.15, 0.15, 0.9)  # 深灰色背景
			style_box.border_width_left = 1
			style_box.border_width_right = 1
			style_box.border_width_top = 1
			style_box.border_width_bottom = 1
			style_box.border_color = Color(0.5, 0.5, 0.5, 1.0)  # 灰色边框
			style_box.corner_radius_top_left = 3
			style_box.corner_radius_top_right = 3
			style_box.corner_radius_bottom_left = 3
			style_box.corner_radius_bottom_right = 3
			background.add_theme_stylebox_override("panel", style_box)

# 属性显示功能已移除，现在使用独立的角色属性窗口

func _on_equipment_slot_input(event: InputEvent, slot_type):
	# 检查UI是否被锁定
	if is_ui_locked:
		return
	
	if event is InputEventMouseButton:
		if event.button_index == MOUSE_BUTTON_LEFT:
			if event.pressed:
				# 鼠标按下，开始计时
				mouse_press_time = Time.get_ticks_msec() / 1000.0
				mouse_press_slot = equipment_slots[slot_type]
				is_mouse_pressed = true
			else:
				# 鼠标释放，判断是单击还是拖拽
				if is_mouse_pressed and mouse_press_slot == equipment_slots[slot_type] and not is_dragging:
					var press_duration = (Time.get_ticks_msec() / 1000.0) - mouse_press_time
					var equipment = ItemManager.get_equipped_item(slot_type)
					
					if press_duration < DRAG_THRESHOLD_TIME:
						# 短按：选中装备槽并显示信息
						_select_equipment_slot(slot_type)
						if equipment != null:
							_show_item_tooltip(equipment, event.global_position)
							_show_item_info(equipment)
							# 检查双击卸下装备
							if _is_double_click(mouse_press_slot):
								if ItemManager.unequip_item(slot_type):
									item_unequipped.emit(slot_type)
						else:
							# 空槽位也可以选中
							pass
					else:
						# 长按：开始拖拽（如果有装备）
						if equipment != null:
							var slot_ui = equipment_slots[slot_type]
							_start_drag(slot_ui, equipment, "equipment", slot_type)
				
				# 重置按压状态
				is_mouse_pressed = false
				mouse_press_slot = null
		elif event.button_index == MOUSE_BUTTON_RIGHT and event.pressed:
			var equipment = ItemManager.get_equipped_item(slot_type)
			if equipment != null:
				# 右键选中装备槽并显示信息
				_select_equipment_slot(slot_type)
				_show_item_tooltip(equipment, event.global_position)
			else:
				# 右键点击空装备槽，选中该槽位
				_select_equipment_slot(slot_type)

func _on_inventory_slot_input(event: InputEvent, item_type, index: int):
	# 检查UI是否被锁定
	if is_ui_locked:
		return
	
	if event is InputEventMouseButton:
		var inventory = ItemManager.get_inventory_by_type(item_type)
		if index >= inventory.size():
			return
		
		var inventory_slot = inventory[index]
		var slot_ui = inventory_slots[item_type][index]
		if event.button_index == MOUSE_BUTTON_LEFT:
			if event.pressed:
				# 鼠标按下，开始计时
				mouse_press_time = Time.get_ticks_msec() / 1000.0
				mouse_press_slot = slot_ui
				is_mouse_pressed = true
			else:
				# 鼠标释放，判断是单击还是拖拽
				if is_mouse_pressed and mouse_press_slot == slot_ui:
					var press_duration = (Time.get_ticks_msec() / 1000.0) - mouse_press_time
					
					if press_duration < DRAG_THRESHOLD_TIME:
						# 短按：处理选中和多选逻辑
						if not inventory_slot.is_empty() and inventory_slot.item_data != null:
							# 检查是否按住Ctrl键进行多选
							if Input.is_action_pressed("ui_select_multiple") or Input.is_key_pressed(KEY_CTRL):
								# 多选模式：切换选中状态
								_toggle_item_selection(item_type, index)
							else:
								# 单选模式：切换选中状态并显示信息
								_toggle_item_selection(item_type, index)
								_show_item_tooltip(inventory_slot.item_data, event.global_position)
								# 检查双击使用物品
								if _is_double_click(slot_ui):
									if inventory_slot.item_data.type == ItemManager.ItemType.EQUIPMENT:
										# 装备物品 - 只有装备类型的背包才能装备
										if item_type == ItemManager.ItemType.EQUIPMENT and ItemManager.equip_item(index):
											var equipment_data = inventory_slot.item_data as ItemManager.EquipmentData
											if equipment_data != null:
												item_equipped.emit(equipment_data.slot, equipment_data)
									elif inventory_slot.item_data.type == ItemManager.ItemType.CONSUMABLE:
										# 使用消耗品 - 只有消耗品类型的背包才能使用
										if item_type == ItemManager.ItemType.CONSUMABLE:
											# 先获取消耗品数据，然后使用
											var consumable_data = inventory_slot.item_data as ItemManager.ConsumableData
											if ItemManager.use_item(index):
												# 调用实际的使用效果
												_use_consumable(consumable_data)
												item_used.emit(consumable_data)
					else:
						# 长按：开始拖拽（如果有物品）
						if not inventory_slot.is_empty():
							_start_drag(slot_ui, inventory_slot.item_data, "inventory", index, item_type)
				
				# 重置按压状态
				is_mouse_pressed = false
				mouse_press_slot = null
		elif event.button_index == MOUSE_BUTTON_RIGHT and event.pressed:
			if not inventory_slot.is_empty() and inventory_slot.item_data != null:
				# 右键选中物品并显示信息
				_select_inventory_item(item_type, index)
				_show_item_tooltip(inventory_slot.item_data, event.global_position)

func _use_consumable(consumable):
	# 检查UI是否被锁定
	if is_ui_locked:
		return
	
	match consumable.effect_type:
		"heal":
			# 为玩家恢复生命值
			if PlayerStatsManager != null:
				PlayerStatsManager.heal(consumable.effect_value)
			else:
				print("PlayerStatsManager不可用")
			
			# 为已上阵的幻兽恢复生命值
			_heal_active_phantom_beasts(consumable.effect_value)
			
		"mana":
			pass
		"experience":
			# 为玩家增加经验值
			if PlayerStatsManager != null:
				PlayerStatsManager.gain_experience(consumable.effect_value)
				print("玩家获得 %d 点经验值" % consumable.effect_value)
			else:
				print("PlayerStatsManager不可用")
			
			# 为已上阵的幻兽增加经验值
			_give_experience_to_active_phantom_beasts(consumable.effect_value)
			
		"full_restore":
			# 完全恢复玩家生命值和魔法值
			if PlayerStatsManager != null:
				PlayerStatsManager.heal_full()
				PlayerStatsManager.restore_mp_full()
			else:
				print("PlayerStatsManager不可用")
			
			# 完全恢复已上阵幻兽的生命值
			_heal_active_phantom_beasts_full()
			
		_:
			print("未知的消耗品效果: ", consumable.effect_type)

func _heal_active_phantom_beasts(heal_amount: int):
	"""为已上阵的幻兽恢复指定数量的生命值"""
	if PhantomBeastManager == null:
		print("PhantomBeastManager不可用")
		return
	
	# 获取当前上阵的幻兽列表
	var active_formation = PhantomBeastManager.get_active_formation_data()
	if active_formation.is_empty():
		print("当前没有上阵的幻兽")
		return
	
	var healed_count = 0
	for beast_data in active_formation:
		var beast_id = beast_data.get("unique_id", "")
		if beast_id == "":
			continue
		
		# 只为活着的幻兽恢复生命值
		if not beast_data.get("is_alive", true):
			continue
		
		# 获取幻兽当前生命值和最大生命值
		var current_hp = beast_data.get("current_hp", 0)
		var max_hp = beast_data.get("stats", {}).get("max_hp", 0)
		
		# 如果生命值已满，跳过
		if current_hp >= max_hp:
			continue
		
		# 计算恢复后的生命值
		var new_hp = min(current_hp + heal_amount, max_hp)
		
		# 更新幻兽生命值
		if PhantomBeastManager.set_phantom_beast_hp(beast_id, new_hp):
			healed_count += 1
			var beast_name = PhantomBeastManager.get_phantom_beast_display_name(beast_id)
			print("幻兽 %s 恢复了 %d 点生命值 (%d/%d)" % [beast_name, new_hp - current_hp, new_hp, max_hp])
	
	if healed_count > 0:
		print("共有 %d 只上阵幻兽恢复了生命值" % healed_count)
	else:
		print("没有幻兽需要恢复生命值")

func _heal_active_phantom_beasts_full():
	"""完全恢复已上阵幻兽的生命值"""
	if PhantomBeastManager == null:
		print("PhantomBeastManager不可用")
		return
	
	# 获取当前上阵的幻兽列表
	var active_formation = PhantomBeastManager.get_active_formation_data()
	if active_formation.is_empty():
		print("当前没有上阵的幻兽")
		return
	
	var healed_count = 0
	for beast_data in active_formation:
		var beast_id = beast_data.get("unique_id", "")
		if beast_id == "":
			continue
		
		# 只为活着的幻兽恢复生命值
		if not beast_data.get("is_alive", true):
			continue
		
		# 获取幻兽最大生命值
		var max_hp = beast_data.get("stats", {}).get("max_hp", 0)
		var current_hp = beast_data.get("current_hp", 0)
		
		# 如果生命值已满，跳过
		if current_hp >= max_hp:
			continue
		
		# 完全恢复生命值
		if PhantomBeastManager.set_phantom_beast_hp(beast_id, max_hp):
			healed_count += 1
			var beast_name = PhantomBeastManager.get_phantom_beast_display_name(beast_id)
			print("幻兽 %s 生命值已完全恢复 (%d/%d)" % [beast_name, max_hp, max_hp])
	
	if healed_count > 0:
		print("共有 %d 只上阵幻兽完全恢复了生命值" % healed_count)
	else:
		print("没有幻兽需要恢复生命值")

func _give_experience_to_active_phantom_beasts(exp_amount: int):
	"""为已上阵的幻兽增加经验值"""
	if PhantomBeastManager == null:
		print("PhantomBeastManager不可用")
		return
	
	# 获取当前上阵的幻兽列表
	var active_formation = PhantomBeastManager.get_active_formation_data()
	if active_formation.is_empty():
		print("当前没有上阵的幻兽")
		return
	
	var exp_gained_count = 0
	for beast_data in active_formation:
		var beast_id = beast_data.get("unique_id", "")
		if beast_id == "":
			continue
		
		# 只为活着的幻兽增加经验值
		if not beast_data.get("is_alive", true):
			continue
		
		# 获取幻兽名称（避免重复声明）
		var beast_name = PhantomBeastManager.get_phantom_beast_display_name(beast_id)
		
		# 检查幻兽是否已达到最大等级
		var current_level = beast_data.get("level", 1)
		if current_level >= PhantomBeastManager.max_phantom_beast_level:
			print("幻兽 %s 已达到最大等级，无法获得经验" % beast_name)
			continue
		
		# 为幻兽增加经验值
		PhantomBeastManager.add_phantom_beast_experience(beast_id, exp_amount)
		exp_gained_count += 1
	
	if exp_gained_count > 0:
		print("上阵幻兽(%d只)获得经验值: %d" % [exp_gained_count, exp_amount])
	else:
		print("没有幻兽能够获得经验值")

func _on_slot_mouse_entered(slot_ui: Control, _slot_type):
	# 装备槽悬停效果 - 改变边框颜色为金色
	var background = slot_ui.get_child(0) as Panel
	if background:
		var style_box = background.get_theme_stylebox("panel").duplicate() as StyleBoxFlat
		style_box.border_color = Color(1.0, 0.8, 0.2, 1.0)  # 金色边框
		background.add_theme_stylebox_override("panel", style_box)

func _on_inventory_slot_mouse_entered(slot_ui: Control, _item_type, _index: int):
	# 物品槽悬停效果 - 改变边框颜色为白色
	var background = slot_ui.get_child(0) as Panel
	if background:
		var style_box = background.get_theme_stylebox("panel").duplicate() as StyleBoxFlat
		style_box.border_color = Color(0.8, 0.8, 0.8, 1.0)  # 亮白色边框
		background.add_theme_stylebox_override("panel", style_box)

func _on_slot_mouse_exited():
	# 只在拖拽状态下才恢复样式，避免不必要的闪烁
	if not is_dragging:
		return
	
	# 恢复装备槽原始边框颜色
	for slot_type in equipment_slots:
		var slot_ui = equipment_slots[slot_type]
		# 检查是否是当前选中的装备槽，如果是则跳过
		if selected_slot == slot_ui:
			continue
		
		var background = slot_ui.get_child(0) as Panel
		if background:
			var style_box = background.get_theme_stylebox("panel").duplicate() as StyleBoxFlat
			style_box.border_color = Color(0.6, 0.6, 0.8, 1.0)  # 浅蓝色边框
			background.add_theme_stylebox_override("panel", style_box)
	
	# 恢复物品槽原始边框颜色
	for item_type in inventory_slots:
		for slot_ui in inventory_slots[item_type]:
			# 检查是否是当前选中的背包物品槽，如果是则跳过
			if selected_inventory_slot == slot_ui:
				continue
			
			var background = slot_ui.get_child(0) as Panel
			if background:
				var style_box = background.get_theme_stylebox("panel").duplicate() as StyleBoxFlat
				style_box.border_color = Color(0.5, 0.5, 0.5, 1.0)  # 灰色边框
				background.add_theme_stylebox_override("panel", style_box)

func _show_item_tooltip(item, _position: Vector2):
	var tooltip_text = "[b]%s[/b]\n" % item.name
	tooltip_text += "%s\n\n" % item.description
	
	if item.type == ItemManager.ItemType.EQUIPMENT:
		var equipment = item
		tooltip_text += "等级要求: %d\n" % equipment.level_requirement
		if equipment.enhancement_level > 0:
			tooltip_text += "强化等级: +%d\n" % equipment.enhancement_level
		tooltip_text += "\n[b]属性:[/b]\n"
		if equipment.get_total_strength() > 0:
			tooltip_text += "力量: +%d\n" % equipment.get_total_strength()
		if equipment.get_total_agility() > 0:
			tooltip_text += "敏捷: +%d\n" % equipment.get_total_agility()
		if equipment.get_total_intelligence() > 0:
			tooltip_text += "智力: +%d\n" % equipment.get_total_intelligence()
		if equipment.get_total_stamina() > 0:
			tooltip_text += "耐力: +%d\n" % equipment.get_total_stamina()
		if equipment.get_total_spirit() > 0:
			tooltip_text += "精神: +%d\n" % equipment.get_total_spirit()
		if equipment.get_total_physical_defense() > 0:
			tooltip_text += "物理防御: +%d\n" % equipment.get_total_physical_defense()
	elif item.type == ItemManager.ItemType.CONSUMABLE:
		var consumable = item
		tooltip_text += "效果: %s %d\n" % [consumable.effect_type, consumable.effect_value]
	
	print("物品信息: ", tooltip_text)

func _on_equipment_changed(_slot, _equipment):
	if visible:
		print("_on_equipment_changed")
		_update_equipment_display()

func _on_inventory_changed():
	if visible:
		print("_on_inventory_changed")
		_update_inventory_display()

func _on_close_requested():
	hide()

func toggle_visibility():
	"""切换窗口显示状态"""
	if visible:
		hide()
	else:
		# 显示窗口前动态设置窗口大小
		_setup_window_size()
		show()
		_update_display()
		
		# 打印窗口大小信息
		var player_hud_size = player_hud.size if player_hud else Vector2.ZERO
		var window_size = size
		var inventory_panel_size = inventory_panel.size if inventory_panel else Vector2.ZERO
		print("=== 背包窗口大小信息 ===")
		print("PlayerHUD大小: ", player_hud_size)
		print("背包窗口大小: ", window_size)
		print("背包面板大小: ", inventory_panel_size)
		print("========================")

func _update_gold_display(gold_amount: int):
	gold_label.text = "金币: " + str(gold_amount)

func _on_sell_button_pressed():
	## 直接卖出选中的物品
	# 检查UI是否被锁定
	if is_ui_locked:
		return
	
	if selected_items_for_sale.size() == 0:
		# 如果没有选中物品，提示用户
		print("请先选择要卖出的物品（按住Ctrl键可多选）")
		return
	
	# 显示卖出确认对话框
	_show_sell_confirmation_dialog()

func _clear_selected_items():
	## 清除选中的物品
	selected_items_for_sale.clear()
	_update_inventory_display()  # 刷新显示，移除选中效果
	_update_select_all_button_text()  # 更新全选按钮状态

func _show_sell_confirmation_dialog():
	# 检查是否有选中的物品
	if selected_items_for_sale.size() == 0:
		confirm_label.text = "请先选择要卖出的物品！"
		confirm_sell_button.text = "确定"
		confirm_sell_button.disabled = true
		cancel_sell_button.text = "返回"
		_show_confirm_panel()
		return
	
	# 按物品ID分组统计不同种类的物品
	var unique_items = {}
	var total_value = 0
	
	for item_info in selected_items_for_sale:
		var item_data = ItemManager.get_item_data(item_info.item_id)
		var quantity = item_info.quantity
		var value = int(item_data.value * 0.5) * quantity  # 卖出价格为原价的50%
		total_value += value
		
		# 按物品ID分组
		var key = str(item_info.item_type) + "_" + item_info.item_id
		if unique_items.has(key):
			unique_items[key].quantity += quantity
			unique_items[key].value += value
		else:
			unique_items[key] = {
				"name": item_data.name,
				"quantity": quantity,
				"value": value
			}
	
	# 获取物品种类数量
	var item_types_count = unique_items.size()
	
	# 根据物品种类数量决定显示方式
	var confirm_text = ""
	if item_types_count > 10:
		# 超过10种物品时，只显示总数和总金额
		confirm_text = "确认卖出选中的物品？\n\n共 %d 种物品\n总价值: %d金币" % [item_types_count, total_value]
	else:
		# 10种及以下时，详细列出每种物品
		var item_list = ""
		for key in unique_items.keys():
			var item = unique_items[key]
			item_list += "- %s x%d (价值: %d金币)\n" % [item.name, item.quantity, item.value]
		
		confirm_text = "确认卖出以下物品？\n\n%s\n总价值: %d金币" % [item_list, total_value]
	
	confirm_label.text = confirm_text
	confirm_sell_button.text = "确认"
	confirm_sell_button.disabled = false
	cancel_sell_button.text = "取消"
	
	# 显示确认面板
	_show_confirm_panel()

# 显示确认面板（悬浮在背包中央）
func _show_confirm_panel():
	confirm_panel.visible = true

# 隐藏确认面板
func _hide_confirm_panel():
	confirm_panel.visible = false

# 确认卖出按钮处理
func _on_confirm_sell_pressed():
	# 如果按钮被禁用，只是隐藏确认面板
	if confirm_sell_button.disabled:
		_hide_confirm_panel()
		return
	
	# 执行卖出操作
	_confirm_sell_items()

# 取消卖出按钮处理
func _on_cancel_sell_pressed():
	_hide_confirm_panel()

func _confirm_sell_items():
	var total_gold = 0
	
	# 按物品ID分组，避免重复处理同一物品
	var items_to_sell = {}
	for item_info in selected_items_for_sale:
		var item_id = item_info.item_id
		var item_type = item_info.item_type
		var quantity = item_info.quantity
		
		var key = str(item_type) + "_" + item_id
		if items_to_sell.has(key):
			items_to_sell[key].quantity += quantity
		else:
			items_to_sell[key] = {
				"item_type": item_type,
				"item_id": item_id,
				"quantity": quantity
			}
	
	# 执行卖出操作
	for key in items_to_sell.keys():
		var item_info = items_to_sell[key]
		var item_type = item_info.item_type
		var item_id = item_info.item_id
		var quantity = item_info.quantity
		
		# 获取物品数据计算价格
		var item_data = ItemManager.get_item_data(item_id)
		if item_data != null:
			# 移除物品
			var removed_quantity = ItemManager.remove_item_from_inventory(item_id, quantity, item_type)
			if removed_quantity > 0:
				# 按实际移除的数量计算金币（原价的50%）
				var actual_gold = int(item_data.value * 0.5) * removed_quantity
				PlayerStatsManager.add_gold(actual_gold)
				total_gold += actual_gold
				print("卖出 %s x%d，获得 %d 金币" % [item_data.name, removed_quantity, actual_gold])
			else:
				print("卖出失败：%s" % item_data.name)
	
	print("卖出完成，总共获得 %d 金币" % total_gold)
	_hide_confirm_panel()
	_clear_selected_items()

func _on_select_all_button_pressed():
	## 全选当前标签页的所有物品
	# 检查UI是否被锁定
	if is_ui_locked:
		return
	
	# 获取当前标签页类型
	var current_tab = tab_container.current_tab
	var tab_names = [ItemManager.ItemType.EQUIPMENT, ItemManager.ItemType.CONSUMABLE, ItemManager.ItemType.MATERIAL]
	
	if current_tab >= tab_names.size():
		return
	
	var current_item_type = tab_names[current_tab]
	var inventory = ItemManager.get_inventory_by_type(current_item_type)
	
	# 检查是否已经全选
	var all_selected = true
	for i in range(inventory.size()):
		if not inventory[i].is_empty():
			if not _is_item_selected_for_sale(current_item_type, i):
				all_selected = false
				break
	
	if all_selected:
		# 如果已经全选，则取消全选
		for i in range(inventory.size()):
			if not inventory[i].is_empty():
				# 从选中列表中移除
				for j in range(selected_items_for_sale.size() - 1, -1, -1):
					if selected_items_for_sale[j].item_type == current_item_type and selected_items_for_sale[j].index == i:
						selected_items_for_sale.remove_at(j)
						break
		select_all_button.text = "全选"
		print("取消全选当前标签页物品")
	else:
		# 全选当前标签页的所有物品
		for i in range(inventory.size()):
			if not inventory[i].is_empty():
				# 检查是否已经选中
				var already_selected = false
				for item_info in selected_items_for_sale:
					if item_info.item_type == current_item_type and item_info.index == i:
						already_selected = true
						break
				
				if not already_selected:
					var item_data = inventory[i].item_data
					var quantity = inventory[i].quantity
					var item_info = {
						"item_type": current_item_type,
						"index": i,
						"item_id": item_data.id,
						"quantity": quantity
					}
					selected_items_for_sale.append(item_info)
		select_all_button.text = "取消全选"
		print("全选当前标签页物品")
	
	# 更新全选按钮状态
	_update_select_all_button_text()
	
	# 更新全选按钮状态
	_update_select_all_button_text()
	
	# 更新显示
	_update_inventory_display()

func _update_select_all_button_text():
	## 更新全选按钮的文本状态
	
	# 获取当前标签页类型
	var current_tab = tab_container.current_tab
	var tab_names = [ItemManager.ItemType.EQUIPMENT, ItemManager.ItemType.CONSUMABLE, ItemManager.ItemType.MATERIAL]
	
	if current_tab >= tab_names.size():
		return
	
	var current_item_type = tab_names[current_tab]
	var inventory = ItemManager.get_inventory_by_type(current_item_type)
	
	# 检查当前标签页是否全选
	var all_selected = true
	var has_items = false
	for i in range(inventory.size()):
		if not inventory[i].is_empty():
			has_items = true
			if not _is_item_selected_for_sale(current_item_type, i):
				all_selected = false
				break
	
	if has_items and all_selected:
		select_all_button.text = "取消全选"
	else:
		select_all_button.text = "全选"

func _on_tab_changed(_tab_index: int):
	## 标签页切换时更新全选按钮状态
	# 检查UI是否被锁定
	if is_ui_locked:
		return
	
	# 清空选中的待售物品列表
	selected_items_for_sale.clear()
	print("切换标签页，已清空选中的待售物品")
	
	# 更新全选按钮状态
	_update_select_all_button_text()
	
	# 更新显示以清除多选高亮
	_update_inventory_display()

func _on_sort_button_pressed():
	# 检查UI是否被锁定
	if is_ui_locked:
		return
	
	# 整理当前标签页的背包
	var current_tab = tab_container.current_tab
	var tab_names = [ItemManager.ItemType.EQUIPMENT, ItemManager.ItemType.CONSUMABLE, ItemManager.ItemType.MATERIAL]
	
	if current_tab < tab_names.size():
		var current_item_type = tab_names[current_tab]
		ItemManager.sort_inventory(current_item_type)
		print("背包整理完成")

func _toggle_item_selection(item_type, index: int):
	## 切换物品选中状态（用于多选和卖出）
	
	var inventory = ItemManager.get_inventory_by_type(item_type)
	if index >= inventory.size() or inventory[index].is_empty():
		return
	
	var item_data = inventory[index].item_data
	var item_id = item_data.id
	var quantity = inventory[index].quantity
	
	# 检查是否已选中
	var existing_index = -1
	for i in range(selected_items_for_sale.size()):
		if selected_items_for_sale[i].item_type == item_type and selected_items_for_sale[i].index == index:
			existing_index = i
			break
	
	if existing_index >= 0:
		# 取消选中
		selected_items_for_sale.remove_at(existing_index)
		print("取消选中: %s" % item_data.name)
		# 如果取消选中后还有其他选中的物品，显示最后一个选中的物品信息
		if selected_items_for_sale.size() > 0:
			var last_selected = selected_items_for_sale[-1]
			var last_item_data = ItemManager.get_item_data(last_selected.item_id)
			if last_item_data:
				# 设置选中状态变量
				selected_inventory_type = last_selected.item_type
				selected_inventory_index = last_selected.index
				_show_item_info(last_item_data)
		else:
			# 没有选中物品时显示默认提示信息
			item_info_label.text = "点击物品查看详细信息"
			item_info_panel.visible = true
	else:
		# 选中物品
		var item_info = {
			"item_type": item_type,
			"index": index,
			"item_id": item_id,
			"quantity": quantity
		}
		selected_items_for_sale.append(item_info)
		print("选中: %s x%d" % [item_data.name, quantity])
		# 设置选中状态变量
		selected_inventory_type = item_type
		selected_inventory_index = index
		# 显示当前选中物品的信息
		_show_item_info(item_data)
	
	# 清除单选状态（多选时清除单选）
	_clear_inventory_selection()
	
	# 更新全选按钮状态
	_update_select_all_button_text()
	
	# 更新显示
	_update_inventory_display()

func _is_item_selected_for_sale(item_type, index: int) -> bool:
	# 检查物品是否被选中用于卖出
	for item_info in selected_items_for_sale:
		if item_info.item_type == item_type and item_info.index == index:
			return true
	return false

func _select_inventory_item(item_type, index: int):
	## 选中背包物品，显示详细信息（单选模式）
	var inventory = ItemManager.get_inventory_by_type(item_type)
	if index >= inventory.size() or inventory[index].is_empty():
		return
	
	# 清除之前的选中状态
	_clear_inventory_selection()
	
	# 清除多选状态（单选时清除所有多选）
	selected_items_for_sale.clear()
	
	# 设置新的选中状态
	selected_inventory_type = item_type
	selected_inventory_index = index
	selected_inventory_slot = inventory_slots[item_type][index]
	
	# 更新视觉效果
	_update_inventory_selection_visual()
	
	# 显示物品信息
	var item_data = inventory[index].item_data
	_show_item_info(item_data)
	
	# 更新显示以清除多选高亮
	_update_inventory_display()
	_update_select_all_button_text()

func _clear_inventory_selection():
	# 清除背包物品选中状态
	if selected_inventory_slot:
		_update_inventory_slot_visual(selected_inventory_slot, false)
	
	selected_inventory_slot = null
	selected_inventory_type = null
	selected_inventory_index = -1

func _update_inventory_selection_visual():
	# 更新背包物品选中状态的视觉效果
	if selected_inventory_slot:
		_update_inventory_slot_visual(selected_inventory_slot, true)

func _update_inventory_slot_visual(slot_ui: Control, is_selected: bool):
	# 更新背包物品槽的视觉效果
	var background = slot_ui.get_child(0) as Panel
	if background:
		if is_selected:
			# 选中状态 - 绿色边框
			var style_box = StyleBoxFlat.new()
			style_box.bg_color = Color(0.15, 0.15, 0.15, 0.9)  # 深灰色背景
			style_box.border_width_left = 3
			style_box.border_width_right = 3
			style_box.border_width_top = 3
			style_box.border_width_bottom = 3
			style_box.border_color = Color(0.0, 1.0, 0.0, 1.0)  # 绿色边框
			style_box.corner_radius_top_left = 3
			style_box.corner_radius_top_right = 3
			style_box.corner_radius_bottom_left = 3
			style_box.corner_radius_bottom_right = 3
			background.add_theme_stylebox_override("panel", style_box)
		else:
			# 未选中状态 - 恢复原始样式
			var style_box = StyleBoxFlat.new()
			style_box.bg_color = Color(0.15, 0.15, 0.15, 0.9)  # 深灰色背景
			style_box.border_width_left = 1
			style_box.border_width_right = 1
			style_box.border_width_top = 1
			style_box.border_width_bottom = 1
			style_box.border_color = Color(0.5, 0.5, 0.5, 1.0)  # 灰色边框
			style_box.corner_radius_top_left = 3
			style_box.corner_radius_top_right = 3
			style_box.corner_radius_bottom_left = 3
			style_box.corner_radius_bottom_right = 3
			background.add_theme_stylebox_override("panel", style_box)

func _show_item_info(item_data):
	# 在物品信息面板显示物品详细信息
	if item_info_panel and item_info_label:
		var info_text = "[b]%s[/b]\n" % item_data.name
		# 显示稀有度信息
		var rarity_name = ItemManager.get_rarity_name(item_data.rarity)
		var rarity_color = ItemManager.get_rarity_color(item_data.rarity)
		# 将颜色转换为十六进制字符串用于富文本
		var color_hex = "#%02x%02x%02x" % [int(rarity_color.r * 255), int(rarity_color.g * 255), int(rarity_color.b * 255)]
		info_text += "[color=%s]稀有度: %s[/color]\n" % [color_hex, rarity_name]
		info_text += "%s\n\n" % item_data.description
		
		if item_data.type == ItemManager.ItemType.EQUIPMENT:
			var equipment = item_data as ItemManager.EquipmentData
			info_text += "等级要求: %d\n" % equipment.level_requirement
			
			# 显示强化等级
			if equipment.enhancement_level > 0:
				info_text += "强化等级: +%d\n" % equipment.enhancement_level
			else:
				info_text += "强化等级: +0\n"
			
			# 显示强化费用
			if equipment.can_enhance():
				var cost = _get_enhancement_cost(equipment.enhancement_level)
				info_text += "强化费用: %d 金币\n" % cost
				var success_rate = _get_enhancement_success_rate(equipment.enhancement_level)
				info_text += "成功率: %d%%\n" % success_rate
			else:
				info_text += "已达到最大强化等级\n"
			
			info_text += "\n[b]属性:[/b]\n"
			
			# 显示基础属性和强化后属性
			if equipment.strength > 0:
				var base_str = equipment.strength
				var total_str = equipment.get_total_strength()
				if equipment.enhancement_level > 0:
					info_text += "力量: %d (+%d)\n" % [base_str, total_str - base_str]
				else:
					info_text += "力量: %d\n" % base_str
			
			if equipment.agility > 0:
				var base_agi = equipment.agility
				var total_agi = equipment.get_total_agility()
				if equipment.enhancement_level > 0:
					info_text += "敏捷: %d (+%d)\n" % [base_agi, total_agi - base_agi]
				else:
					info_text += "敏捷: %d\n" % base_agi
			
			if equipment.intelligence > 0:
				var base_int = equipment.intelligence
				var total_int = equipment.get_total_intelligence()
				if equipment.enhancement_level > 0:
					info_text += "智力: %d (+%d)\n" % [base_int, total_int - base_int]
				else:
					info_text += "智力: %d\n" % base_int
			
			if equipment.stamina > 0:
				var base_sta = equipment.stamina
				var total_sta = equipment.get_total_stamina()
				if equipment.enhancement_level > 0:
					info_text += "耐力: %d (+%d)\n" % [base_sta, total_sta - base_sta]
				else:
					info_text += "耐力: %d\n" % base_sta
			
			if equipment.spirit > 0:
				var base_spi = equipment.spirit
				var total_spi = equipment.get_total_spirit()
				if equipment.enhancement_level > 0:
					info_text += "精神: %d (+%d)\n" % [base_spi, total_spi - base_spi]
				else:
					info_text += "精神: %d\n" % base_spi
			
			if equipment.physical_defense > 0:
				var base_def = equipment.physical_defense
				var total_def = equipment.get_total_physical_defense()
				if equipment.enhancement_level > 0:
					info_text += "物理防御: %d (+%d)\n" % [base_def, total_def - base_def]
				else:
					info_text += "物理防御: %d\n" % base_def
			
			# 设置当前强化物品信息
			current_enhance_item = equipment
			
			# 根据当前选中的装备来源设置强化相关变量
			if selected_equipment_type != null:
				# 装备来自装备槽
				current_enhance_slot_type = selected_equipment_type
				current_enhance_inventory_type = null
				current_enhance_inventory_index = -1
			elif selected_inventory_type != null and selected_inventory_index >= 0:
				# 装备来自背包
				current_enhance_slot_type = null
				current_enhance_inventory_type = selected_inventory_type
				current_enhance_inventory_index = selected_inventory_index
			else:
				# 清除所有强化相关变量
				current_enhance_slot_type = null
				current_enhance_inventory_type = null
				current_enhance_inventory_index = -1
			
			# 显示强化按钮
			if equipment.can_enhance():
				enhance_button.visible = true
				enhance_button.disabled  = false
				enhance_button.text = "强化装备 (费用: %d)" % _get_enhancement_cost(equipment.enhancement_level)
			else:
				enhance_button.visible = false
			
		elif item_data.type == ItemManager.ItemType.CONSUMABLE:
			var consumable = item_data as ItemManager.ConsumableData
			info_text += "效果: %s %d\n" % [consumable.effect_type, consumable.effect_value]
			# 隐藏强化按钮
			enhance_button.visible = false
			current_enhance_item = null
		else:
			# 非装备物品，隐藏强化按钮
			enhance_button.visible = false
			current_enhance_item = null
		
		item_info_label.text = info_text
		item_info_panel.visible = true

func _select_equipment_slot(slot_type):
	# 选中装备槽，显示装备信息
	# 清除之前的选中状态
	_clear_equipment_selection()
	
	# 设置新的选中状态
	selected_equipment_type = slot_type
	selected_equipment_slot = equipment_slots[slot_type]
	
	# 更新视觉效果
	_update_equipment_slot_selection_visual()
	
	# 更新装备信息显示
	_update_equipment_info_display()

func _clear_equipment_selection():
	# 清除装备选中状态
	if selected_equipment_slot:
		_update_equipment_slot_visual(selected_equipment_slot, false)
	
	selected_equipment_slot = null
	selected_equipment_type = null

func _update_equipment_slot_selection_visual():
	# 更新装备槽选中状态的视觉效果
	if selected_equipment_slot:
		_update_equipment_slot_visual(selected_equipment_slot, true)

func _update_equipment_slot_visual(slot_ui: Control, is_selected: bool):
	# 更新装备槽的视觉效果
	var background = slot_ui.get_child(0) as Panel
	if background:
		if is_selected:
			# 选中状态 - 绿色边框
			var style_box = StyleBoxFlat.new()
			style_box.bg_color = Color(0.15, 0.15, 0.15, 0.9)  # 深灰色背景
			style_box.border_width_left = 3
			style_box.border_width_right = 3
			style_box.border_width_top = 3
			style_box.border_width_bottom = 3
			style_box.border_color = Color(0.0, 1.0, 0.0, 1.0)  # 绿色边框
			style_box.corner_radius_top_left = 3
			style_box.corner_radius_top_right = 3
			style_box.corner_radius_bottom_left = 3
			style_box.corner_radius_bottom_right = 3
			background.add_theme_stylebox_override("panel", style_box)
		else:
			# 未选中状态 - 恢复原始样式
			var style_box = StyleBoxFlat.new()
			style_box.bg_color = Color(0.15, 0.15, 0.15, 0.9)  # 深灰色背景
			style_box.border_width_left = 1
			style_box.border_width_right = 1
			style_box.border_width_top = 1
			style_box.border_width_bottom = 1
			style_box.border_color = Color(0.5, 0.5, 0.5, 1.0)  # 灰色边框
			style_box.corner_radius_top_left = 3
			style_box.corner_radius_top_right = 3
			style_box.corner_radius_bottom_left = 3
			style_box.corner_radius_bottom_right = 3
			background.add_theme_stylebox_override("panel", style_box)

func _update_equipment_info_display():
	# 更新装备属性显示面板
	if not selected_equipment_type or not item_info_panel or not item_info_label:
		return
	
	var equipment = ItemManager.get_equipped_item(selected_equipment_type)
	if equipment:
		_show_item_info(equipment)
	else:
		# 显示空槽位信息
		var slot_name = _get_slot_display_name(selected_equipment_type)
		item_info_label.text = "[b]%s[/b]\n\n当前没有装备" % slot_name
		item_info_panel.visible = true

func _get_slot_display_name(slot_type) -> String:
	# 获取装备槽位的显示名称
	match slot_type:
		ItemManager.EquipmentSlot.WEAPON:
			return "武器"
		ItemManager.EquipmentSlot.HELMET:
			return "头盔"
		ItemManager.EquipmentSlot.CHEST:
			return "胸甲"
		ItemManager.EquipmentSlot.LEGS:
			return "腿甲"
		ItemManager.EquipmentSlot.GLOVES:
			return "手套"
		ItemManager.EquipmentSlot.BOOTS:
			return "鞋子"
		ItemManager.EquipmentSlot.RING1:
			return "戒指1"
		ItemManager.EquipmentSlot.RING2:
			return "戒指2"
		ItemManager.EquipmentSlot.NECKLACE:
			return "项链"
		ItemManager.EquipmentSlot.EARRING:
			return "耳环"
		_:
			return "未知装备槽"

func _get_enhancement_cost(current_level: int) -> int:
	# 计算强化费用，等级越高费用越高
	var base_cost = 100
	return base_cost * (current_level + 1) * (current_level + 1)

func _get_enhancement_success_rate(current_level: int) -> int:
	# 根据强化等级返回成功率
	match current_level:
		0, 1, 2:  # 0->1, 1->2, 2->3
			return 100
		3, 4, 5:  # 3->4, 4->5, 5->6
			if current_level == 3:
				return 70
			elif current_level == 4:
				return 65
			else:
				return 60
		6, 7, 8:  # 6->7, 7->8, 8->9
			return 60
		9:  # 9->10
			return 50
		10:  # 10->11
			return 50
		11:  # 11->12
			return 40
		12:  # 12->13
			return 30
		13:  # 13->14
			return 20
		14:  # 14->15
			return 10
		_:
			return 0

func _on_enhance_button_pressed():
	# 强化按钮点击处理
	if not current_enhance_item:
		return
	
	# 检查金币是否足够
	var cost = _get_enhancement_cost(current_enhance_item.enhancement_level)
	if PlayerStatsManager.get_gold() < cost:
		print("金币不足，无法强化")
		return
	
	# 检查是否为高风险强化（10级以上失败会损毁装备）
	if current_enhance_item.enhancement_level >= 10:
		_show_high_risk_confirmation(cost)
	else:
		# 直接进行强化
		_proceed_enhancement(cost)

func _show_high_risk_confirmation(cost: int):
	# 显示高风险强化确认对话框
	var risk_confirm_panel = Panel.new()
	var risk_confirm_label = RichTextLabel.new()
	var button_container = HBoxContainer.new()
	var confirm_button = Button.new()
	var cancel_button = Button.new()
	var vbox = VBoxContainer.new()
	
	# 设置面板样式
	risk_confirm_panel.custom_minimum_size = Vector2(400, 200)
	risk_confirm_panel.position = Vector2(
		(get_viewport().get_visible_rect().size.x - 400) / 2,
		(get_viewport().get_visible_rect().size.y - 200) / 2
	)
	
	# 设置警告文本
	var warning_text = "[color=red][b]警告！[/b][/color]\n\n"
	warning_text += "当前装备强化等级为 +%d\n" % current_enhance_item.enhancement_level
	warning_text += "强化失败将会导致装备完全损毁！\n\n"
	warning_text += "强化费用：%d 金币\n" % cost
	warning_text += "成功率：%d%%\n\n" % _get_enhancement_success_rate(current_enhance_item.enhancement_level)
	warning_text += "是否确定要继续强化？"
	
	risk_confirm_label.text = warning_text
	risk_confirm_label.bbcode_enabled = true  # 启用BBCode解析
	risk_confirm_label.fit_content = true  # 自适应内容大小
	risk_confirm_label.scroll_active = false  # 禁用滚动
	
	# 设置按钮
	confirm_button.text = "确定强化"
	cancel_button.text = "取消"
	confirm_button.pressed.connect(_confirm_high_risk_enhancement.bind(risk_confirm_panel, cost))
	cancel_button.pressed.connect(_cancel_high_risk_enhancement.bind(risk_confirm_panel))
	
	# 组装UI
	button_container.add_child(cancel_button)
	button_container.add_child(confirm_button)
	vbox.add_child(risk_confirm_label)
	vbox.add_child(button_container)
	risk_confirm_panel.add_child(vbox)
	
	# 设置布局
	vbox.set_anchors_and_offsets_preset(Control.PRESET_FULL_RECT)
	vbox.add_theme_constant_override("separation", 15)
	risk_confirm_label.size_flags_vertical = Control.SIZE_EXPAND_FILL
	button_container.size_flags_horizontal = Control.SIZE_SHRINK_CENTER
	button_container.add_theme_constant_override("separation", 20)
	
	# 添加到场景
	get_viewport().add_child(risk_confirm_panel)

func _confirm_high_risk_enhancement(risk_panel: Panel, cost: int):
	# 确认高风险强化
	risk_panel.queue_free()
	_proceed_enhancement(cost)

func _cancel_high_risk_enhancement(risk_panel: Panel):
	# 取消高风险强化
	risk_panel.queue_free()

func _proceed_enhancement(cost: int):
	# 执行强化流程
	# 扣除金币
	PlayerStatsManager.add_gold(-cost)
	_update_gold_display(PlayerStatsManager.get_gold())
	
	# 开始强化动画
	_start_enhancement_animation()

func _start_enhancement_animation():
	# 开始强化动画
	enhance_button.disabled = true
	enhance_button.text = "强化中..."
	
	# 锁定整个UI，禁用所有交互
	is_ui_locked = true
	_set_ui_interaction_enabled(false)
	
	# 创建动画计时器
	var timer = Timer.new()
	add_child(timer)
	timer.wait_time = randf_range(1.0, 3.0)  # 1-3秒随机动画时间
	timer.one_shot = true
	timer.timeout.connect(_finish_enhancement_animation.bind(timer))
	timer.start()

func _finish_enhancement_animation(timer: Timer):
	# 完成强化动画，显示结果
	timer.queue_free()
	
	if not current_enhance_item:
		return
	
	# 计算强化结果
	var success_rate = _get_enhancement_success_rate(current_enhance_item.enhancement_level)
	var is_success = randf() * 100 < success_rate
	
	# 处理强化结果
	var result_text = ""
	var old_level = current_enhance_item.enhancement_level
	
	if is_success:
		# 强化成功
		current_enhance_item.enhancement_level += 1
		result_text = "强化成功！\n%s +%d -> +%d" % [current_enhance_item.name, old_level, current_enhance_item.enhancement_level]
		# 强化成功后自动保存游戏
		if GameSaveManager != null:
			GameSaveManager.manual_save()
			print("强化成功，游戏已自动保存")
	else:
		# 强化失败，根据等级处理
		if old_level >= 10:  # 10级以上失败装备损毁
			result_text = "强化失败！\n%s 已损毁" % current_enhance_item.name
			_destroy_equipment()
		elif old_level >= 6:  # 6-9级失败等级下降
			var new_level = _get_failure_downgrade_level(old_level)
			current_enhance_item.enhancement_level = new_level
			result_text = "强化失败！\n%s +%d -> +%d" % [current_enhance_item.name, old_level, new_level]
		else:  # 0-5级失败保持等级
			result_text = "强化失败！\n%s 等级保持 +%d" % [current_enhance_item.name, old_level]
	
	# 显示强化结果
	_show_enhancement_result(result_text)

func _get_failure_downgrade_level(current_level: int) -> int:
	# 获取强化失败后的等级
	match current_level:
		6:  # 6->7失败回到5
			return 5
		7:  # 7->8失败回到6
			return 6
		8:  # 8->9失败回到7
			return 7
		9:  # 9->10失败回到3
			return 3
		_:
			return current_level

func _destroy_equipment():
	# 销毁装备
	if current_enhance_slot_type != null:
		# 装备在装备槽中，直接删除而不是卸下
		ItemManager.equipment_slots[current_enhance_slot_type] = null
		ItemManager.equipment_changed.emit(current_enhance_slot_type, null)
	elif current_enhance_inventory_type != null and current_enhance_inventory_index >= 0:
		# 装备在背包中
		var inventory = ItemManager.get_inventory_by_type(current_enhance_inventory_type)
		if current_enhance_inventory_index < inventory.size():
			inventory[current_enhance_inventory_index] = ItemManager.InventorySlot.new()
			ItemManager.inventory_changed.emit()
	
	# 清除当前强化物品信息
	current_enhance_item = null
	current_enhance_slot_type = null
	current_enhance_inventory_type = null
	current_enhance_inventory_index = -1
	
	# 隐藏物品信息面板和强化按钮
	enhance_button.visible = false
	
	# 清除装备选中状态
	_clear_equipment_selection()
	_clear_inventory_selection()
	
	# 强制更新界面显示
	_update_display()

func _show_enhancement_result(result_text: String):
	# 清除之前的强化结果面板
	if current_enhancement_result_panel != null and is_instance_valid(current_enhancement_result_panel):
		current_enhancement_result_panel.queue_free()
		current_enhancement_result_panel = null
	
	# 解锁UI，恢复交互
	is_ui_locked = false
	_set_ui_interaction_enabled(true)
	
	# 在屏幕中央显示强化结果
	var result_panel = Panel.new()
	var result_label = Label.new()
	var confirm_button = Button.new()
	var vbox = VBoxContainer.new()
	
	# 保存当前结果面板引用
	current_enhancement_result_panel = result_panel
	
	# 设置面板样式
	result_panel.custom_minimum_size = Vector2(300, 150)
	result_panel.position = Vector2(
		(get_viewport().get_visible_rect().size.x - 300) / 2,
		(get_viewport().get_visible_rect().size.y - 150) / 2
	)
	
	# 设置标签
	result_label.text = result_text
	result_label.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTER
	result_label.vertical_alignment = VERTICAL_ALIGNMENT_CENTER
	result_label.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
	
	# 设置按钮
	confirm_button.text = "确定"
	confirm_button.pressed.connect(_close_enhancement_result.bind(result_panel))
	
	# 组装UI
	vbox.add_child(result_label)
	vbox.add_child(confirm_button)
	result_panel.add_child(vbox)
	
	# 设置布局
	vbox.set_anchors_and_offsets_preset(Control.PRESET_FULL_RECT)
	vbox.add_theme_constant_override("separation", 10)
	result_label.size_flags_vertical = Control.SIZE_EXPAND_FILL
	confirm_button.size_flags_horizontal = Control.SIZE_SHRINK_CENTER
	
	# 添加到场景
	get_viewport().add_child(result_panel)
	
	# 只有在装备还存在时才重新启用强化按钮
	if current_enhance_item != null:
		enhance_button.disabled = false
		# 更新物品信息显示
		_show_item_info(current_enhance_item)
	else:
		# 装备已损毁，隐藏强化按钮
		enhance_button.visible = false
	
	# 更新显示
	_update_display()

func _close_enhancement_result(result_panel: Panel):
	# 关闭强化结果面板
	result_panel.queue_free()
	# 清除引用
	if current_enhancement_result_panel == result_panel:
		current_enhancement_result_panel = null

func _set_ui_interaction_enabled(enabled: bool):
	"""设置UI交互状态"""
	# 禁用/启用所有按钮
	sell_button.disabled = not enabled
	select_all_button.disabled = not enabled
	sort_button.disabled = not enabled
	
	# 禁用/启用装备槽交互
	for slot_type in equipment_slots.keys():
		var slot = equipment_slots[slot_type]
		if slot != null:
			slot.mouse_filter = Control.MOUSE_FILTER_IGNORE if not enabled else Control.MOUSE_FILTER_PASS
	
	# 禁用/启用背包网格交互
	equipment_grid.mouse_filter = Control.MOUSE_FILTER_IGNORE if not enabled else Control.MOUSE_FILTER_PASS
	consumable_grid.mouse_filter = Control.MOUSE_FILTER_IGNORE if not enabled else Control.MOUSE_FILTER_PASS
	material_grid.mouse_filter = Control.MOUSE_FILTER_IGNORE if not enabled else Control.MOUSE_FILTER_PASS
	
	# 禁用/启用标签页切换
	tab_container.mouse_filter = Control.MOUSE_FILTER_IGNORE if not enabled else Control.MOUSE_FILTER_PASS
